<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/25
 * Time: 17:58
 */

namespace Modules\Api\Service;

use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\BannerRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\StoreOrderRepository;

class ActivityService extends BaseService
{

    /**
     *  按门店获取所有有效的活动列表
     *  hinq 2019 11 25
     *
     **/
    public function get_list()
    {
        try{
            $arr_option['where'] = ['status'=>1];  //有效的活动
            $arr_option['field'] = ['repairstore_id','id','img','title'];
            $arr_option['with'] = ['shop','activity_goods_extend'];
            //get_list_to_now方法添加了条件开始时间 < 当前时间 <  结束时间
            $all_list = ActivityRepository::get_list_to_now( (array) $arr_option )->toArray();
            $all_list = list_page_data_for_api( (array) $all_list );
            foreach ( $all_list['data'] as $key=>$vo ){
                if( empty( $vo['activity_goods_extend'] ) ){
                    unset( $all_list['data'][$key] );
                }
                unset( $all_list['data'][$key]['activity_goods_extend'] );
            }
            $all_list['data'] = array_values( $all_list['data'] );
            return hello_success('ok',$all_list);
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取指定活动的所有商品列表
     *  hinq 2019 11 26
     *  承古纳新启新智
     *  开天普祥劈成果
     *  承露春花频绽蕊
     *  开..........
     **/
    public function get_shop_list( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            //获取指定活动的详细信息
            $arr_option['field'] = ['id','content','status','start_time','over_time','img','repairstore_id','type'];
            $arr_option['with'] = ['activity_goods_extend','activity_extend'=>function( $query ){
                $query->select('id','activity_id','price_all','price');
            }];
            $arr_info = ActivityRepository::get_one( (int) $nId , (array)$arr_option );
            if( empty( $arr_info->first() ) ){
                return hello_error('参数错误');
            }
            $arr_info = $arr_info->toarray();
            if( $arr_info['status']['status'] == 4 ){   //根据当前活动的状态判断
                return hello_error('活动已过期');
            }
            //活动的结束时间小于当前时间    防止活动状态更新不及时
            if( $arr_info['over_time'] < time() ){
                return hello_error('活动已过期');
            }
            if( empty( $arr_info['activity_goods_extend']) ){
                return hello_error('活动暂未添加商品');
            }
            $arr_info['start_time'] = date('Y-m-d H:i:s' , $arr_info['start_time'] );
            $arr_info['over_time'] = date('Y-m-d H:i:s' , $arr_info['over_time'] );
            $ids = '';   //活动设置的所有商品集合

            foreach ( $arr_info['activity_goods_extend'] as $key=>$value){
                $ids .= ',' . $value['goods'];
            }
            $ids = explode( ',' , trim( $ids ,',' ) );
            //获取所有的商品信息
            $arr_option2['field'] = ['id','pic_url','name','price'];
            $arr_option2['with'] = ['product_info'];
            $arr_option2['where'] = ['type'=>3];
            $arrWhereIn =['field'=>'id','ids'=>$ids];
            $arr_goods = GoodsRepository::get_wherein_activity_to_goods( (array) $arr_option2 , (array) $arrWhereIn )->toArray();

            //将获得的商品信息存放到活动对应的模块中
            foreach ( $arr_info['activity_goods_extend'] as $key=>&$value){
                $temp = [];
                foreach ( $arr_goods as $k=>$val){
                    $price = array_column($val['product_info'], 'price');  //获取数组中指定的值
                    $val['price'] = number_format_money(min($price));
                    $goods = explode( ',',$value['goods']);
                    if( in_array( $val['id'] , $goods ) ){
                        $temp[] = $val;
                    }
                    $value['goods_list'] = $temp;
                }
            }
            foreach ( $arr_info['activity_extend'] as $key=>&$val){
                if( $arr_info['type']['type'] == 1 ){
                    $val['msg'] = '满'.round( $val['price_all'] , 2 ) . '减' . round( $val['price'] ,2);
                }else{
                    $val['msg'] = '满'.round( $val['price_all'] , 2 ) . '打' . round( $val['price']  ,2 ) .'折';
                }
            }

            return hello_success('ok',$arr_info );
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取banner列表
     *  hinq 2020 3 3
     *
     **/
    public function banner( array $arr_input ){
        try{
            //type  1:小程序首页banner   2:小程序首页广告图   （暂时去掉）3:道路救援banner图  4:活动主页banner   5:app商户端欢迎页6:年检维修主页

            $arr_input['type'] = empty( $arr_input['type'] ) ? 1 : $arr_input['type'];
            $arr_option['where'] = ['type'=>$arr_input['type'] , 'status'=>1];
            $arr_option['order'] = ['key'=>'sort' , 'value'=>'asc'];
            $arr_option['field'] = ['id','img','link_url'];
            $arr_list = BannerRepository::get_all( (array) $arr_option )->toarray();
            foreach ( $arr_list as &$vo){
                $vo['img'] = oss_full_url( $vo['img']);
            }
            return hello_success('ok',$arr_list );
        }catch (\Exception $exception){
            return hello_error($exception->getMessage());
        }
    }

    /**
     *  获取活动banner列表
     *  hinq 2019 12 09
     *  先获取正在进行中的活动信息，如果没有进行中的活动则获取系统后台配置的banner列表信息
     *  如果有进行中的活动，但是活动中没有设置商品，则获取系统后台配置的banner列表信息
     *  活动的图片可已跳转至活动详情页   系统设置的banner图片不可跳转
     **/
    public function get_activity_banner(){
        try{
            $arr_option['where'] = ['status'=>1];   //正常状态的活动
            $arr_option['field'] = ['img','id'];
            $arr_option['n_per_page'] = 8;
            $arr_option['with'] = ['activity_goods_extend'];
            //获取进行中的活动
            $arr_list = ActivityRepository::get_list_to_now( (array) $arr_option )->toarray();
            $is_banner = false;  //是否获取系统设置的默认活动banner图   false 不请求

            if( empty( $arr_list['data']) ){   //如果活动为空
                $is_banner = true;   //请求默认的活动banner图
            }

            //是否获取平台设置的banner
            $is_skip = true;  //是否跳转页面
            //如果当前活动没有添加商品  当前活动将不展示
            if( $arr_list['data'] ){   //不为空
                foreach ( $arr_list['data'] as $key=>$vo ){
                    if( empty( $vo['activity_goods_extend']) ){  //如果当前活动没有配置商品信息
                        unset( $arr_list['data'][$key]);   //将活动从列表的剔除   不展示当前活动
                    }
                }
                if( count( $arr_list['data'] ) == 0 ){
                    $is_banner = true;
                }
            }
            if( $is_banner ){  //当前时间内没有任何有效的活动  获取平台设置的活动信息
                $banner_option['where'] = ['type'=>4,'status'=>1];    //类型状态为 活动类型
                $banner_option['order'] = ['key'=>'sort','asc'];
                $banner_option['field'] = ['id','img'];
                $banner_option['n_per_page'] = 8;
                $arr_list = BannerRepository::get_list( (array) [] ,  (array) $banner_option )->toarray();
                $is_skip = false;
            }
            $data = [];
            foreach ( $arr_list['data'] as $key=>$vo){
                $data[$key]['id'] = $vo['id'];
                if( !empty(  $vo['img']['full_src'] ) ){
                    $data[$key]['img'] = $vo['img']['full_src'];
                }else{
                    $data[$key]['img'] = oss_full_url( $vo['img'] );
                }
                $data[$key]['is_skip'] = $is_skip;
            }

            $res = [
                'page'=>[
                    'total' => $arr_list['total'],
                    'last_page' => $arr_list['last_page'],
                    'per_page' =>  $arr_list['per_page'],
                    'current_page' =>  $arr_list['current_page']
                ],
                'data'=> array_values($data )
            ];
            return hello_success('ok',$res);
        }catch (\Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取指定商品是否绑定活动
     *  hinq 2020 5 29
     *  平台后台和商户后台允许删除商品 ， 商品删除后 活动就获取不到关联的商品信息
     *  在删除商品操作时 判断当前商品是否被活动所关联 否则不允许删除
     *  商品下架的时候  可以进去商品详情  但是不能下单
     **/
    public function goods_is_del( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            //获取所有未开始 或进行中的活动信息
            $arr_option['where'] = ['status' => 1];
            $arr_option['with'] = ['activity_goods_extend'];
            //获取所有未开始和正在进行中的活动
            $arr_list = ActivityRepository::get_all( $arr_option )->toarray();
            $goods_ids = null;  //所有有效活动关联的所有商品列表
            foreach ( $arr_list as $key => $vo ){
                foreach ( $vo['activity_goods_extend'] as $k => $v ){
                    $goods_ids .= ',' . $v['goods'];
                }
            }
            $goods_ids = explode( ',' , trim( $goods_ids , ',') );
            if( in_array(  $nId , $goods_ids ) ){
                return hello_error('当前商品已参与活动，禁止删除');
            }
            return  hello_success('ok');
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

}